<template>
  <el-dialog :title="!dataForm.skuId ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="80px">
      <el-form-item label="所属商品ID" prop="productId">
        <!-- <el-input v-model="dataForm.productId" placeholder="所属商品ID"></el-input> -->
        <ProductAutocomplete v-model="dataForm.productId"></ProductAutocomplete>
      </el-form-item>
      <el-form-item label="属性组合" prop="attributes">
        <!-- <el-input v-model="dataForm.attributes" placeholder="属性组合（JSON对象）"></el-input> -->
        <!-- <template v-for="(item, index) in saleAttributeList">
          <div class="radio-group">
            <span>{{ item.attrName }}:</span>
            <el-radio aria-hidden="false" v-for="(value, index) in JSON.parse(item.attrValues)"
              v-model="item.checkValue" :label="value" :key="index">{{ value }}</el-radio>
          </div>

        </template> -->
        <el-input v-model="dataForm.attributes" placeholder="属性组合" disabled></el-input>
      </el-form-item>
      <el-form-item label="实际售价（可修改）" prop="price">
        <el-input v-model="dataForm.price" placeholder="实际售价（可修改）"></el-input>
      </el-form-item>
      <el-form-item label="实际库存（实时）" prop="stock">
        <el-input v-model="dataForm.stock" placeholder="实际库存（实时）"></el-input>
      </el-form-item>

      <el-form-item label="累计销量" prop="sales">
        <el-input v-model="dataForm.sales" placeholder="累计销量"></el-input>
      </el-form-item>
      <el-form-item label="sku图片" prop="imgUrl">
        <singleUpload v-model="dataForm.imgUrl"></singleUpload>
      </el-form-item>
      <el-form-item label="内部管理编码（唯一）" prop="skuCode">
        <el-input v-model="dataForm.skuCode" placeholder="内部管理编码（唯一）"></el-input>
      </el-form-item>
      <el-form-item label="SKU创建时间" prop="createdAt">
        <!-- <el-input v-model="dataForm.createdAt" placeholder="SKU创建时间"></el-input> -->
        <el-date-picker v-model="dataForm.createdAt" value-format="yyyy-MM-dd hh:mm:ss" type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>

import singleUpload from '../common/upload/singleUpload.vue';

import ProductAutocomplete from "@/views/modules/common/product-autocomplete"

export default {
  components: {
    singleUpload, ProductAutocomplete
  },
  data() {
    return {
      visible: false,
      // sku详情对象
      dataForm: {
        skuId: 0,
        productId: '',
        attributes: '',
        price: '',
        stock: '',
        sales: '',
        imgUrl: '',
        skuCode: '',
        createdAt: ''
      },
      // 销售属性列表
      // saleAttributeList: [],
      // 组装属性组合JSon对象
      checkValueJson: {},
      dataRule: {
        productId: [
          { required: true, message: '所属商品ID不能为空', trigger: 'blur' }
        ],
        attributes: [
          { required: true, message: '属性组合（JSON对象）不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '实际售价（可修改）不能为空', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '实际库存（实时）不能为空', trigger: 'blur' }
        ],
        sales: [
          { required: true, message: '累计销量不能为空', trigger: 'blur' }
        ],
        imgUrl: [
          { required: true, message: '内部管理编码（唯一）不能为空', trigger: 'blur' }
        ],
        skuCode: [
          { required: true, message: '内部管理编码（唯一）不能为空', trigger: 'blur' }
        ],
        createdAt: [
          { required: true, message: 'SKU创建时间不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init(id) {
      this.dataForm.skuId = id || 0
      this.visible = true
      this.$nextTick(async () => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.skuId) {

          // 获取sku详情
          await this.$http({
            url: this.$http.adornUrl(`/product/sku/info/${this.dataForm.skuId}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.dataForm.productId = data.data.productId
              this.dataForm.attributes = data.data.attributes
              this.dataForm.price = data.data.price
              this.dataForm.stock = data.data.stock
              this.dataForm.sales = data.data.sales
              this.dataForm.imgUrl = data.data.imgUrl
              this.dataForm.skuCode = data.data.skuCode
              this.dataForm.createdAt = data.data.createdAt
            }
          })
          this.getSaleAttr();


        }
      })
    },
    // 表单提交
    dataFormSubmit() {

      // 校验属性组合
      // for (let i = 0; i < this.saleAttributeList.length; i++) {
      //   let attribute = this.saleAttributeList[i];
      //   // 未选择属性值
      //   if (attribute.checkValue === undefined) {
      //     this.$message.error(`请选择${attribute.attrName}`);
      //     return;
      //   }
      //   // 选择了多余的属性值
      //   if (attribute.checkValue !== undefined && attribute.checkValue !== "") {
      //     let index = attribute.attrValues.indexOf(attribute.checkValue);
      //     if (index === -1) {
      //       this.$message.error(`请选择正确的${attribute.attrName}`);
      //       return;
      //     }
      //   }
      //   // 赋值组装对象
      //   this.checkValueJson[attribute.attrName] = attribute.checkValue;
      // }
      // this.dataForm.attributes = JSON.stringify(this.checkValueJson);

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/product/sku/${!this.dataForm.skuId ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'skuId': this.dataForm.skuId || undefined,
              'productId': this.dataForm.productId,
              'attributes': this.dataForm.attributes,
              'price': this.dataForm.price,
              'stock': this.dataForm.stock,
              'sales': this.dataForm.sales,
              'skuCode': this.dataForm.skuCode,
              'imgUrl': this.dataForm.imgUrl,
              'createdAt': this.dataForm.createdAt
            })
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },

    // 获取销售属性列表
    async getSaleAttr() {
      // 获取销售属性列表
      await this.$http({
        url: this.$http.adornUrl(`/product/skuattribute/listByProductId/${this.dataForm.productId}`),
        method: 'get',
      }).then(({ data }) => {
        if (data && data.code === 200) {

          console.log("销售属性列表", data.data);

          this.saleAttributeList = data.data
        }
      })


      // // 解析属性组合
      // let attributes = JSON.parse(this.dataForm.attributes)
      // console.log("attributes", attributes);

      // let keys = Object.keys(attributes);
      // for (let i = 0; i < keys.length; i++) {
      //   let key = keys[i];

      //   for (let j = 0; j < this.saleAttributeList.length; j++) {
      //     let attribute = this.saleAttributeList[j];
      //     if (attribute.attrName === key) {
      //       // 给obj对象添加一个新的响应式属性e
      //       this.$set(attribute, 'checkValue', attributes[key]);
      //       break;
      //     }
      //   }

      // }

      // console.log("saleAttributeList", this.saleAttributeList);
    }
  },
  mounted() {
    this.$refs.radio.$children.forEach((item) => {
      item.$refs.radio.removeAttribute("aria-hidden");
    });

  },

  watch: {
    'dataForm.productId'(newCount, oldCount) {
      this.getSaleAttr();
    }
  }
}
</script>

<style lang="scss" scoped>
// radio checkbox根据你使用组件，自行更换
.radio-group {
  /deep/ .el-radio__original {
    display: none !important;
    /* 隐藏原生 radio 输入，但仍然允许交互 */
  }

  /deep/.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner {
    box-shadow: none !important;
  }
}
</style>
